package com.bigshen.algorithm.gTree.solution05BinaryTreeRightSideView;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 199. Binary Tree Right Side View
 *
 * Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
 *
 * Example:
 *
 * Input: [1,2,3,null,5,null,4]
 * Output: [1, 3, 4]
 * Explanation:
 *
 *    1            <---
 *  /   \
 * 2     3         <---
 *  \     \
 *   5     4       <---
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/binary-tree-right-side-view
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }

    // 遍历每一层级，将每一层级末尾值加入结果集
    public List<Integer> rightSideView(TreeNode root) {

        List<Integer> list = new ArrayList<>();

        if (null == root) {
            return list;
        }

        // 队列 每一层末尾元素放入结果集
        // byQueue(root, list);

        // 递归 每向下一层递归，第一个元素加入结果集
        int depth = 0;
        byRecursion(root, depth, list);

        return list;
    }

    private void byRecursion(TreeNode node, int depth, List<Integer> list) {

        if (depth == list.size()) {
            list.add(node.val);
        }

        if (null != node.right) {
            byRecursion(node.right, depth+1, list);
        }
        if (null != node.left) {
            byRecursion(node.left, depth+1, list);
        }

    }

    private void byQueue(TreeNode node, List<Integer> list) {

        Queue<TreeNode> queue = new LinkedList();
        queue.offer(node);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode element = queue.poll();
                if (i == 0) {
                    // 队列头部元素加入
                    list.add(element.val);
                }
                // 队列，先进先出，优先加右子树
                if (null != element.right) {
                    queue.offer(element.right);
                }
                if (null != element.left) {
                    queue.offer(element.left);
                }
            }
        }

    }

}
